package com.cloudcentral.config;

import com.cloudcentral.util.Result;
import com.cloudcentral.util.WebUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
public class SecurityConfig {
  @Bean
  public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
    return http.anonymous().disable()
        .authorizeHttpRequests()
        .requestMatchers(
            AntPathRequestMatcher.antMatcher(HttpMethod.GET, "/**/*.*"),
            AntPathRequestMatcher.antMatcher(HttpMethod.GET, "/**/api-docs/**")).permitAll()
        .requestMatchers("/user/register").permitAll()
        .anyRequest().access(new CustomAuthorizationManager())
        .and()

        .formLogin().disable()
        .httpBasic().disable()
        .csrf().disable()
        .cors().disable()

        .oauth2ResourceServer().jwt()
        .and()

        .authenticationEntryPoint((request, response, exception) -> WebUtils.writeJson(response, Result.invalid()))
        .accessDeniedHandler((request, response, exception) -> WebUtils.writeJson(response, Result.denied()))
        .and()

        .exceptionHandling()
        .authenticationEntryPoint((request, response, exception) -> WebUtils.writeJson(response, Result.invalid()))
        .accessDeniedHandler((request, response, exception) -> WebUtils.writeJson(response, Result.denied()))
        .and()

        .build();
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }
}
